package com.tusuo.stds.ui;

import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.TextView;

import com.hannesdorfmann.mosby.mvp.MvpActivity;
import com.hannesdorfmann.mosby.mvp.MvpPresenter;
import com.hannesdorfmann.mosby.mvp.MvpView;
import com.tusuo.stds.R;
import com.tusuo.stds.ui.avatar.AvatarActivity_;
import com.tusuo.stds.ui.login.LoginActivity_;
import com.tusuo.stds.ui.name.SetNameActivity_;
import com.tusuo.stds.util.Utils;

import java.util.ArrayList;
import java.util.List;

import myandroid.library.util.ApplicationHelper;

/**
 * @author J.Huang
 * @version 1.0
 *
 */

public abstract class BaseToolbarActivity<V extends MvpView, P extends MvpPresenter<V>>
        extends MvpActivity<V, P> implements ToolbarOwner.IToolbar {

    protected Toolbar mToolbar;
    protected TextView mToolbarTitle;

    protected ToolbarOwner mToolbarOwner;
    protected List<ToolbarOwner.MenuAction> mActionBarMenuActionList;

    // 为了更改menu的字体颜色
    private final ArrayList<View> mMenuItems = new ArrayList<>();

    protected void setupUI(ToolbarOwner.IToolbar iToolbar) {
        int toolbarBgColor = ContextCompat.getColor(this, R.color.colorThemePrimary);
        int toolbarTextColor = ContextCompat.getColor(this, R.color.white);
        setupUI(iToolbar, toolbarBgColor, toolbarTextColor);
    }

    protected void setupUI(ToolbarOwner.IToolbar iToolbar, int toolbarBgColor, int toolbarTextColor) {
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        mToolbar.setBackgroundColor(toolbarBgColor);
        mToolbarTitle = (TextView) findViewById(R.id.tv_toolbar_title);
        mToolbarTitle.setTextColor(toolbarTextColor);

        setSupportActionBar(mToolbar);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 按回退键后强制隐藏软键盘
                Utils.UI.closeInputMethod(BaseToolbarActivity.this);
                onBackPressed();
            }
        });

        mToolbarOwner = new ToolbarOwner(iToolbar);
//        mToolbarOwner.setConfig();
    }

    @Override
    protected void onDestroy() {
        mToolbar = null;
        mToolbarTitle = null;
        mToolbarOwner = null;

        if (mActionBarMenuActionList != null) {
            mActionBarMenuActionList.clear();
        }

        ApplicationHelper.getInstance().removeActivity(this);

        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        return super.dispatchTouchEvent(event);
    }

    /**
     * 重定义返回键操作
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            if (false) {
//                return true;
//            }
//        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (mActionBarMenuActionList != null && mActionBarMenuActionList.size() > 0) {
            for (final ToolbarOwner.MenuAction menuAction : mActionBarMenuActionList) {
                 menu.add(menuAction.title)
                        .setIcon(menuAction.icon)
                        .setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM)
                        .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                            @Override
                            public boolean onMenuItemClick(MenuItem item) {
                                menuAction.action.call();
                                return true;
                            }
                        });
            }

            TextView tvMenuItem = !mMenuItems.isEmpty() ? (TextView) mMenuItems.get(0) : null;
            if (tvMenuItem != null) {
                tvMenuItem.setTextColor(ContextCompat.getColor(this, R.color.colorThemePrimary));
            } else {
                final View decor = getWindow().getDecorView();
                decor.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        // Remove the previously installed OnGlobalLayoutListener
                        decor.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                        // Traverse the decor hierarchy to locate the MenuItem

                        if (BaseToolbarActivity.this instanceof LoginActivity_) {
                            decor.findViewsWithText(mMenuItems, "注册",
                                    View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION);
                        } else if (BaseToolbarActivity.this instanceof SetNameActivity_) {
                            decor.findViewsWithText(mMenuItems, "完成",
                                    View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION);
                        } else if (BaseToolbarActivity.this instanceof AvatarActivity_) {
                            decor.findViewsWithText(mMenuItems, "完成",
                                    View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION);
                        }


                        // Invalidate the options menu to display the new text color
                        invalidateOptionsMenu();
                    }
                });
            }
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
//        if (item.getItemId() == android.R.id.home) {
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void setToolbarTitle(CharSequence title) {
        if (getSupportActionBar() != null) {
            // 默认title居左，不使用
            getSupportActionBar().setTitle("");
            if (mToolbarTitle != null) {
                mToolbarTitle.setText(title);
            }
        }
    }

    /***
     * 使左上角程序图标是否显示，如果设成false，则没有程序图标，仅仅就个标题，否则，显示应用程序图标
     * 对应id为android.R.id.home，对应ActionBar.DISPLAY_SHOW_HOME
     * @param enabled
     */
    @Override
    public void setDisplayShowHomeEnabled(boolean enabled) {
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayShowHomeEnabled(false);
        }
    }

    /***
     *  给左上角图标的左边加上一个返回的图标。对应ActionBar.DISPLAY_HOME_AS_UP
     * @param enabled
     */
    @Override
    public void setUpButtonEnabled(boolean enabled) {
        if (getSupportActionBar() != null) {
            // setHomeButtonEnabled和setDisplayShowHomeEnabled共同起作用。
            // 如果setHomeButtonEnabled设成false，
            // 即使setDisplayShowHomeEnabled设成true，图标也不能点击
            getSupportActionBar().setDisplayHomeAsUpEnabled(enabled);
            // setHomeButtonEnabled 小于4.0版本的默认值为true; 但是在4.0及其以上是false
            // 该方法的作用：决定左上角的图标是否可以点击。没有向左的小图标。true: 图标可以点击; false: 不可以点击。
            getSupportActionBar().setHomeButtonEnabled(enabled);
        }
    }

    @Override
    public void setNavigationIcon(int resId) {
        if (getSupportActionBar() != null && resId != 0) {
            mToolbar.setNavigationIcon(resId);
        }
    }

    @Override
    public void setMenu(List<ToolbarOwner.MenuAction> menuActionList) {
        if (menuActionList != mActionBarMenuActionList) {
            mActionBarMenuActionList = menuActionList;
            invalidateOptionsMenu();
        }
    }

    @Override
    public void setToolbarVisible(boolean visible) {
        if (getSupportActionBar() != null) {
            if (visible) {
                getSupportActionBar().show();
            } else {
                getSupportActionBar().hide();
            }
        }
    }
}
